import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author  lizhen
 * @Date  2021-5-31
 * 定时查杀木马。
 * 每1分钟执行1次/root/kill-crypto.sh
 */

public class RunShell {

    private static final Long INTERVAL_MIN = 1 * 60 * 1000L;

    private static final String SHELL_NAME = "/root/task/kill-crypto.sh";

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {

        long counter = 1;

        while (true) {
            try {
                System.out.println("开始执行第 " + (counter++) + " 次任务 ,@" + SDF.format(new Date(System.currentTimeMillis())));
                Process ps = Runtime.getRuntime().exec(SHELL_NAME);
                ps.waitFor();
                BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                String result = sb.toString();
                sb = new StringBuffer();
                boolean findPID = false;
                for (int i = 0; i < result.length(); i++) {
                    while (result.charAt(i) >= '0' && result.charAt(i) <= '9') {
                        findPID = true;
                        sb.append(result.charAt(i++));
                    }
                    if (findPID) break;
                }
                if (sb.toString().length() > 0) {
                    System.out.println("找到木马，pid = " + sb.toString());
                    ps = Runtime.getRuntime().exec("kill -9 " + sb.toString());
                    ps.waitFor();
                }
                System.out.println("执行任务完毕 ,@" + SDF.format(new Date(System.currentTimeMillis())));
                Thread.sleep(INTERVAL_MIN);
                System.out.println();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
}


